<template>
  <div class="in">
    <div class="tit">
      <div class="ul1">
        <div>全部商品（{{ table.length }}）</div>
      </div>
      <div class="ul2" @click="cartRemove">
        <img class="img" src="@/assets/img/del.png" alt="" /> 删除商品
      </div>
    </div>
    <div class="qie">
      <div class="cai">
        <el-table
          :data="table"
          style="width: 100%"
          @cell-click="cellclick"
          @selection-change="selection"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="imgurl" label="商品图片" align="center">
            <template slot-scope="scope">
              <img class="img1" :src="scope.row.imgurl" />
            </template>
          </el-table-column>
          <el-table-column label="商品信息" prop="name" align="center">
          </el-table-column>
          <el-table-column label="规格" prop="spec" align="center">
          </el-table-column>
          <el-table-column label="店铺名称" prop="shopName" align="center">
          </el-table-column>
          <el-table-column label="数量" prop="num" align="center">
            <template slot-scope="scope">
              <div @click.stop="aa">
                <!-- :max="scope.row.stock" -->
                <el-input-number
                  v-model="scope.row.num"
                  :min="1"
                  size="mini"
                  @change="
                    val => {
                      handleChange(val, scope);
                    }
                  "
                  label="商品数量"
                ></el-input-number>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="总价（￥）" prop="zongjia" align="center">
          </el-table-column>
          <el-table-column label="金额（￥）" prop="price" align="center">
          </el-table-column>
        </el-table>
      </div>
      <div class="di">
        <div class="a">
          已选商品 <span>{{ num }}</span> 件
        </div>
        <div class="a">
          合计（不含运费）：<span>{{ qian }}</span>
        </div>
        <div class="b " :class="{ active: num > 0 }" @click="jieshuan">
          结算
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 购物车列表
      table: [],
      num: 0, //数量
      qian: 0, //钱
      table1: [] //选中的列表
    };
  },
  //注册组件
  components: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getList(), //查询购物车列表
      this.getCountCart(); //查询购物车数量
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //计算属性
  computed: {},
  //方法
  methods: {
    async getCountCart() {
      let res1 = await this.$postRequest("/api/memberCart/getCountCart", {
        userId: localStorage.getItem("userId")
      });
      this.$store.commit("setcart", res1.data);
    },
    jieshuan() {
      if (this.table1.length > 0) {
        let cartList = this.table1.map(res => {
          return res.id;
        });
        console.log(cartList);
        this.$router.push({
          path: "/home/order",
          query: {
            sty: 0,
            userId: localStorage.getItem("userId"),
            cartList
          }
        });
      } else {
        this.$message.error("请选择购买商品");
      }
    },
    // 跳转商品详情
    cellclick(a) {
      let Detail = this.$router.resolve({
        path: "/home/detail",
        query: {
          id: a.goods_id
        }
      });
      window.open(Detail.href, "_blank");
    },
    aa() {},
    async cartRemove() {
      let cartList = this.table1.map(res => {
        return res.id;
      });
      console.log(cartList);
      let res = await this.$postRequest("/api/memberCart/cartRemove", {
        userId: localStorage.getItem("userId"),
        cartList
      });
      console.log(res);
      this.$message.success(res.msg);
      this.getList();
      this.getCountCart();
    },
    // 获取购物车列表
    async getList() {
      let res = await this.$postRequest("/api/memberCart/getList", {
        userId: localStorage.getItem("userId")
      });
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].zongjia = (res.data[i].price * res.data[i].num).toFixed(2);
      }
      this.table = res.data;
      console.log("getList", this.table, res.data);
    },
    // 选择购物车
    selection(e) {
      console.log(e);
      let num = 0,
        qian = 0;
      for (let i = 0; i < e.length; i++) {
        num += e[i].num;
        qian += e[i].num * e[i].price;
      }
      this.num = num;
      this.qian = qian.toFixed(2);
      this.table1 = e;
    },
    async handleChange(a, b) {
      // max="scope.row.stock"
      if (a > b.row.stock) {
        this.$message.error("选中数量超出库存数量");
        this.$nextTick(() => {
          console.log(this.table, this.table[b.$index], b.$index, b);
          this.table[b.$index].num = b.row.stock;
        });
        return;
      }
      let tab = this.table;
      let res = await this.$postRequest("/api/memberCart/editCart", {
        userId: localStorage.getItem("userId"),
        cartId: tab[b.$index].id,
        num: a
      });
      this.getCountCart();
      tab[b.$index].zongjia = (tab[b.$index].price * tab[b.$index].num).toFixed(
        2
      );
      this.table = tab;
      var c = false;
      for (let i = 0; i < this.table1.length; i++) {
        if (this.table1[i].id == b.row.id) {
          c = true;
          break;
        }
      }
      if (c) {
        this.selection(this.table1);
      }
    },
    // 查询购物车数量
    async getCountCart() {
      let res = await this.$postRequest("/api/memberCart/getCountCart", {
        userId: localStorage.getItem("userId")
      });
      console.log(res);
      if (res.code == 0) {
        this.$store.commit("setcart", res.data);
      } else {
        this.$message.error(res.msg);
      }
    }
  }
};
</script>
<style scoped lang='scss'>
.in {
  width: 100%;
  overflow-y: auto;
  background: #ffffff;
  border: 1px solid #eeeeee;
  .tit {
    width: 100%;
    height: 50px;
    background: #ffffff;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ul1 {
      display: flex;
      height: 100%;
      align-items: center;
      div {
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #000000;
        margin-left: 20px;
      }
    }
    .ul2 {
      padding-right: 20px;
      cursor: pointer;
      color: #1a69e0;
      display: flex;
      align-items: center;
      .img {
        width: 20px;
        height: 20px;
        margin-right: 8px;
      }
      &:hover {
        opacity: 0.8;
      }
    }
  }
  .cai {
    margin: 30px 20px;
    border: 1px solid #eeeeee;
    border-bottom: none;
    .img1 {
      width: 70px;
      height: 70px;
    }
    /deep/ .el-input-number {
      width: 110px;
      height: 30px;
    }
  }
  .di {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px 20px 0;
    .a {
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #666666;
      margin-right: 20px;
      span {
        color: #de3232;
        font-size: 24px;
      }
    }
    .b {
      width: 150px;
      height: 60px;
      line-height: 60px;
      background: #a0a0a0;
      text-align: center;
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #ffffff;
      cursor: pointer;
    }
    .active {
      // background: #a0a0a0;
      background-color: rgba(26, 105, 224, 0.05);
      border: 1px solid #1a69e0;
      color: #1a69e0;
    }
  }
}
</style>